package com.longway.common.safe;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jfinal.handler.Handler;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;
import com.longway.common.kit.AesKit;
import com.longway.common.token.utils.RSAUtils;

/**
 * 参数解密
 * @author ryc
 */
public class EdecryHandler extends Handler{

    private  final String privatekey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKxpJwq17F5D+6OfmukGIDxTVRM+2/ubUYeYyRX3L40P9J1A7X8hRofI6zEk1OMRu6OfcKjrL30cpITzuuHe6/GrugWKNku6d6nEWEJBeEu6+4W6x8uuKUjn9GXU98wHNrthRTD5e5xMBoWlyiv4Hl3DoKFdNMOs/1+hRGKMrOB/AgMBAAECgYBYyu7ofTj2c1ytsA0/5X/EkcZG2yDAPAWJKA6n2V4L8COyuTWXO7PvSnKWJLnfF8rjQcHrvPQAIzg3oK6mlQA94q4JSTXPW5Vex2zvpoxnDc5r2/+KfgINN6aF4vLDJxPSe97mn442iEnkOBwYk3ELb3NZWEz6T7N2dEB1JOGRwQJBAPs1o7iT8wvww3WQTtOIgCFja9+Oql4z3mRtornUJdNGHyQ4DNy6Qyv00uh0ej89dB5xl5xxKC14Ls6fO43VaUMCQQCvstTPJzoHYlqHurrpcjXUiBHEkISKDbkzOKCwxBiRFpUzwdIl8Q4zDt9xqsJpf+WyisbrQFdh0BQvXoM+/OoVAkBAkIy/x+bTztGtyaU44QBtlGwJTVWkWJh0H2mPcWM3ZfJjELTdllHlXktGy4kP7++EU5Wv87Vr2lPNb0eTMKKZAkAXZtFTeh0PiLkYJPXqTA0BbtI3BSyyGpvVR7CXerbu9DwRNbqg1ReYE14NjLnyRVe5zSQrh1lcLNPTb1o51IP1AkEAnXADepxGCq+zswYTwZfkJF5bxyzBwAVjQXctyqhTIlc/HJOQ3fgJB3z4GvkznTgqKMb4/CEzPtO17KcPwUwrDw==";
    
	@Override
	public void handle(String target, HttpServletRequest request,
			HttpServletResponse response, boolean[] isHandled) {
		String contentType = request.getContentType();
		String securitykey = request.getHeader("Security-Key");
		//带.表示非action请求，忽略(其实不太严谨,如果是伪静态，比如.html会被错误地排除);
		if (target.indexOf(".") == -1){
			/**
			 * java端配置,根据后端配置的正则来匹配是否对请求过来的数据进行解密处理,但是后端的解密是依赖前端的加密的,
			 * 所以还不如根据前端传递过来的标志
			 * 来决定后端是否解密更为稳妥
			 */
			if(StrKit.notBlank(securitykey)){
				try {
					securitykey = RSAUtils.decryptDataOnJava(securitykey, privatekey);
                    //获取request的请求数据
					String bodyInfoEn="";
					int isJson = 0;
					if(StrKit.notBlank(contentType) && contentType.contains("application/json")){
						bodyInfoEn = HttpKit.readData(request);
						isJson = 1;
					}else{
						bodyInfoEn = request.getParameter("content");
					}
                    if (StrKit.notBlank(bodyInfoEn)) {
                        String bodyInfoDe = AesKit.decrypt(bodyInfoEn, securitykey);//对content进行解密
                        if (StrKit.notBlank(bodyInfoDe)) {
                        	if(isJson==0){
                        		 //解析body里面的参数与uri头里面的参数信息
	                            Map<String, String[]> parametersMap = getParamterMap(request, bodyInfoDe);
	                            //由于request请求没有修改参数的权限，使用篡改后的request代替原先的
	                            request  = new EdecryHttpServletRequestWrapper(request, parametersMap);
                        	}else{
                        		request  = new EdecryHttpServletRequestWrapper(request,bodyInfoDe);
                        	}
                           
                        }
                    }
                } catch (Exception e) {
                   e.printStackTrace();
                }
			}
        }
		next.handle(target, request, response, isHandled);
	}
	
	 /**
     * 获取解析好的参数信息
     *
     * @param req
     * @param bodyInfoDe
     * @return Map<String,String[]>
     */
    private Map<String,String[]> getParamterMap(HttpServletRequest req, String bodyInfoDe) throws UnsupportedEncodingException {
        Map<String, String[]> parametersMap = new HashMap<String, String[]>(20);
        String[] paramFlex = bodyInfoDe.split("&"); //通过&进行分割
        for (String s : paramFlex) {
            String[] pairparam = s.split("=");
            if (pairparam.length > 1) {
                parametersMap.put(pairparam[0], new String[]{pairparam[1]});
            }
        }
        return parametersMap;
    }
}
